05. Readers & Writers
Readers and Writers
In this section, you will learn how to read and write character data using the Reader
and Writer
abstract classes.
ND079 JPND C2 L02 A07 Readers And Writers
Readers / Writers
Readers and Writers are the next level of abstraction built on top of input and output streams. These interfaces read and write text characters.
Reader Example
char[] data = new char[10];
Reader reader =
Files.newBufferedReader(Path.of("test"), StandardCharsets.UTF_8);
while (reader.read(data) != -1) {
useData(data);
}
reader.close();
Just like input streams, Reader
s are usually created with the Files API. But instead of reading byte
s, we are reading char
s. There's also a StandardCharset
, which we'll cover that in more detail in the next video.
Writer Example
Writer writer =
Files.newBufferedWriter(Path.of("test"),
StandardCharsets.UTF_8);
writer.write("hello, world");
writer.close(); // Close the "test" file
The Writer
is pretty much what you would expect. This time we are writing encoded String
s of data instead of raw byte
s.
If you're just itching to see a coding demo using readers and writers, rest assured there's one on the very next page! I decided to save the demo for the discussion on character encodings.